<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="register"
    :footer="null"
    @close="handleClose"
    :title="displayModuleTitle"
    width="90%"
  >
    <a-form
      v-if="
        Object.keys(checkResult).length > 0 ||
        checkFormSchema.filter((item) => item.component == 'FormItem').length == 0
      "
      :model="checkResult"
      ref="checkFormRef"
      :rules="rules"
      layout="vertical"
    >
      <div style="display: flex; justify-content: space-between; margin-bottom: 5px">
        <h2
          >{{ formOption?.title }}
          <a-tooltip>
            <template #title>编辑检查表</template>
            <a-button size="small" type="text" @click="onEditCheckFormButtonClick()"
              ><Icon icon="ant-design:edit-outlined" color="#53afe0" :size="20"></Icon
            ></a-button>
          </a-tooltip>
        </h2>
        <a-tooltip>
          <template #title>新增分组</template>
          <a-button type="success" @click="onAddCheckFormGroupButtonClick"
            ><Icon icon="ant-design:plus-outlined" :size="22"></Icon
          ></a-button>
        </a-tooltip>
      </div>
      <div style="height: calc(100vh - 140px); overflow-y: auto">
        <div v-for="(item, index) in checkFormSchema">
          <a-divider orientation="left" v-if="item.component == 'Divider'"
            >{{ item.label }}
            <a-tooltip>
              <template #title>编辑检查分组</template>
              <a-button size="small" type="text" @click="onEditCheckFormGroupButtonClick(item.id)"
                ><Icon icon="ant-design:edit-outlined" color="#53afe0" :size="17"></Icon
              ></a-button>
            </a-tooltip>

            <a-tooltip>
              <template #title>批量添加检查项</template>
              <a-button size="small" type="text" @click="onBulkAddCheckFormItemButtonClick(item.id)"
                ><Icon icon="ant-design:plus-circle-twotone" color="#58c325" :size="17"></Icon
              ></a-button>
            </a-tooltip>

            <a-popconfirm
              title="是否确认删除检查分组?"
              ok-text="确认"
              cancel-text="取消"
              @confirm="onDeleteCheckFormGroupButtonClick(item.id)"
              ><a-button size="small" type="text"
                ><Icon icon="ant-design:delete-outlined" color="#c15363" :size="17"></Icon
              ></a-button> </a-popconfirm
          ></a-divider>
          <a-form-item
            v-if="item.component == 'FormItem'"
            :name="item.field"
            :labelCol="{ span: 24 }"
            :required="item.required"
            :wrapperCol="{ span: 24 }"
            style="margin-bottom: 5px; padding: 5px"
          >
            <a-row class="mb-1">
              <a-col>
                <span v-if="item.required" style="color: red; margin-right: 5px">*</span>
                <label :for="item.field">{{ item.label }}</label>
                <a-tooltip>
                  <template #title>编辑检查项</template>
                  <a-button
                    size="small"
                    type="text"
                    @click="onEditCheckFormItemButtonClick(item.parentId, item.id)"
                    ><Icon icon="ant-design:form-outlined" color="#43cfad" :size="17"></Icon
                  ></a-button>
                </a-tooltip>

                <a-popconfirm
                  title="是否确认删除检查项?"
                  ok-text="确认"
                  cancel-text="取消"
                  @confirm="onDeleteCheckFormItemButtonClick(item.id)"
                  ><a-button size="small" type="text"
                    ><Icon icon="ant-design:delete-outlined" color="#c15363" :size="17"></Icon
                  ></a-button>
                </a-popconfirm>
              </a-col>
            </a-row>
            <a-radio-group
              style="margin-bottom: 10px"
              v-model:value="checkResult[item.field].value"
              :options="item.options"
            ></a-radio-group>

            <a-input
              style="margin-bottom: 5px"
              :placeholder="item.description ?? '请补充说明'"
              v-show="
                item.contenttype == 1 ||
                (item.contenttype == 3 &&
                  checkResult[item.field].value == item.options[item.options.length - 1].value)
              "
              v-model:value="checkResult[item.field].description"
            />
            <BasicUpload
              style="margin-top: 5px"
              v-if="
                item.minimgcount &&
                (item.contenttype == 1 ||
                  (item.contenttype == 3 &&
                    checkResult[item.field].value == item.options[item.options.length - 1].value))
              "
              :maxSize="1024"
              :multiple="true"
              v-model:value="checkResult[item.field].images"
              :api="uploadApi"
              :uploadParams="{ system: 'ehs', module: 'attachment', title: '' }"
              :showPreviewNumber="true"
              :showUploadList="{
                showPreviewIcon: true,
                showRemoveIcon: true,
                showDownloadIcon: false,
              }"
            />
          </a-form-item>
        </div>
      </div>
    </a-form>
    <AddOrUpdateCheckForm @register="registerAddOrUpdateCheckFormModal" @success="reloadData" />
    <AddOrUpdateCheckGroupForm
      @register="registerAddOrUpdateCheckGroupForm"
      @success="reloadData"
    />
    <AddOrUpdateCheckItem @register="registerAddOrUpdateCheckItemForm" @success="reloadData" />
    <BulkAddCheckItem @register="registerBulkAddCheckItemForm" @success="reloadData" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { computed, defineComponent, ref, unref, watch } from 'vue';
  import { BasicModal, useModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getCheckFormFull, saveCheckRecord } from '/@/api/ehs/checkForm';
  import { deleteCheckGroup, deleteCheckItem } from '/@/api/ehs/checkForm';
  import type { FormInstance } from 'ant-design-vue';
  import { getCheckRecordByDataId } from '/@/api/ehs/checkForm';
  const { createMessage } = useMessage();
  import { BasicUpload } from '/@/components/Upload';
  import { uploadApi } from '/@/api/platform/upload';
  import AddOrUpdateCheckGroupForm from './AddOrUpdateCheckGroupForm.vue';
  import AddOrUpdateCheckItem from './AddOrUpdateCheckItem.vue';
  import BulkAddCheckItem from './BulkAddCheckItem.vue';
  import AddOrUpdateCheckForm from './AddOrUpdateCheckForm.vue';
  import { Icon } from '/@/components/Icon';
  import { Item } from 'ant-design-vue/lib/menu';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  export default defineComponent({
    components: {
      BasicDrawer,
      BasicForm,
      BasicUpload,
      AddOrUpdateCheckForm,
      AddOrUpdateCheckGroupForm,
      AddOrUpdateCheckItem,
      BulkAddCheckItem,
      Icon,
    },
    props: ['mode'],
    name: 'CheckFormDrawer',
    emits: ['success'],
    setup(props, { emit }) {
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const checkFormRef = ref<FormInstance>();
      const dataId = ref(); // 选择的检查表id
      const orgcode = ref();
      const formOption = ref();
      const checkResult = ref({}); // 检查填写结果
      const checkFormSchema = ref<formSchema>([]); // 检查表配置
      const rules = ref({});
      const [registerAddOrUpdateCheckFormModal, { openModal: openAddOrUpdateCheckForm }] =
        useModal();
      const [registerAddOrUpdateCheckGroupForm, { openModal: openAddOrUpdateCheckFormGroupModal }] =
        useModal();
      const [registerAddOrUpdateCheckItemForm, { openModal: openAddOrUpdateCheckFormItemModal }] =
        useModal();
      const [registerBulkAddCheckItemForm, { openModal: openBulkAddCheckItemModal }] = useModal();
      const [register, { closeDrawer }] = useDrawerInner((data) => {
        checkFormRef.value?.clearValidate();
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (unrefData?.dataId) {
            dataId.value = unrefData.dataId;
            orgcode.value = unrefData.orgcode;
            reloadData();
          }
        }
      });

      function reloadData() {
        checkResult.value = {};
        rules.value = {};
        getCheckFormFull(dataId.value).then((res) => {
          formOption.value = res;
          let schema = [];
          formOption.value.groups?.forEach((item, index) => {
            schema.push({
              id: item.groupid,
              index: index + 1,
              label: index + 1 + '. ' + item.title,
              component: 'Divider',
              required: false,
              field: item.title,
              childrenLength: item.items?.length ?? 0,
            });
            if (item.items?.length > 0) {
              item.items?.forEach((item2, index2) => {
                schema.push({
                  id: item2.itemid,
                  index: index2 + 1,
                  component: 'FormItem',
                  childrenLength: item.items?.length,
                  field: item2.title,
                  contenttype: item2.contenttype,
                  parentId: item.groupid,
                  parentGroupName: item.title,
                  minimgcount: item2.minimgcount,
                  label: index + 1 + '.' + (index2 + 1) + ' ' + item2.title,
                  description: item2.description,
                  required: item2.notnull,
                  options: JSON.parse(item2.options),
                });
              });
            }
          });
          checkFormSchema.value = schema;
          console.log(checkFormSchema.value, 'checkFormSchema');
          checkFormSchema.value
            .filter((item) => item.component == 'FormItem')
            ?.forEach((item) => {
              checkResult.value[item.field] = {
                value: '',
                description: '',
                images: [],
              };
              // console.log(item, 'validateitem');
              if (item.required) {
                rules.value[item.field] = [
                  {
                    required: true,
                    validator: (rule, value) => ruleValidate(rule, value, item),
                  },
                ];
              } else {
                rules.value[item.field] = [
                  {
                    validator: (rule, value) => ruleValidate(rule, value, item),
                  },
                ];
              }
            });
        });
      }

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      /**
       * 打开编辑检查表窗口
       * @param record
       */
      function onEditCheckFormButtonClick() {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '检查表管理',
          operateType: OperationTypeEnum.EDIT,
          dataId: dataId.value,
          orgcode: orgcode.value,
        };
        openAddOrUpdateCheckForm(true, propsData);
      }

      // 新增分组
      function onAddCheckFormGroupButtonClick() {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '分组管理',
          operateType: OperationTypeEnum.ADD,
          tableid: dataId.value,
        };
        openAddOrUpdateCheckFormGroupModal(true, propsData);
      }

      // 编辑分组
      function onEditCheckFormGroupButtonClick(groupid) {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '分组管理',
          operateType: OperationTypeEnum.EDIT,
          tableid: dataId.value,
          groupid: groupid,
        };
        openAddOrUpdateCheckFormGroupModal(true, propsData);
      }

      /**
       * 批量新增项目
       */
      function onBulkAddCheckFormItemButtonClick(groupid) {
        console.log(groupid);
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '分组项目管理',
          operateString: '批量添加检查项',
          tableid: dataId.value,
          groupid: groupid,
        };
        openBulkAddCheckItemModal(true, propsData);
      }

      // 编辑项目
      function onEditCheckFormItemButtonClick(groupid, itemid) {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '分组项目管理',
          operateType: OperationTypeEnum.EDIT,
          tableid: dataId.value,
          groupid: groupid,
          itemid: itemid,
        };
        openAddOrUpdateCheckFormItemModal(true, propsData);
      }

      //删除分组
      function onDeleteCheckFormGroupButtonClick(groupid) {
        deleteCheckGroup(groupid)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              reloadData();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      //删除项目
      function onDeleteCheckFormItemButtonClick(itemid) {
        deleteCheckItem(itemid)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              reloadData();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**生成校验规则 */
      function ruleValidate(rule, value, item) {
        console.log(value, item, 'validate');
        if (item.required) {
          if (!value.value || value.value == '') {
            return Promise.reject(rule.field + '不能为空');
          }
          if (
            item.contenttype == 1 ||
            (item.contenttype == 3 && value.value == item.options[item.options.length - 1].value)
          ) {
            if (!value.description || value.description == '') {
              return Promise.reject(rule.field + '补充内容不能为空');
            }
          }
        }
        if (
          item.minimgcount &&
          (item.contenttype == 1 ||
            (item.contenttype == 3 &&
              value.value == item.options[item.options.length - 1].value)) &&
          value.images.length < item.minimgcount
        ) {
          return Promise.reject(rule.field + '至少上传' + item.minimgcount + '张图片');
        }
        return Promise.resolve();
      }

      function handleClose() {
        closeDrawer();
        emit('success');
      }

      return {
        rules,
        uploadApi,
        register,
        checkFormSchema,
        checkFormRef,
        checkResult,
        formOption,
        closeDrawer,
        displayModuleTitle,
        reloadData,
        registerAddOrUpdateCheckFormModal,
        registerAddOrUpdateCheckGroupForm,
        registerAddOrUpdateCheckItemForm,
        registerBulkAddCheckItemForm,
        onEditCheckFormButtonClick,
        onAddCheckFormGroupButtonClick,
        onEditCheckFormGroupButtonClick,
        onBulkAddCheckFormItemButtonClick,
        onEditCheckFormItemButtonClick,
        onDeleteCheckFormItemButtonClick,
        onDeleteCheckFormGroupButtonClick,
        handleClose,
      };
    },
  });
</script>
<style scoped>
  .headButton {
    display: flex;
    justify-content: flex-end;
  }
  .checkItemTitle {
    font-size: 16px;
    margin-bottom: 5px;
  }
  :deep(.ant-divider-horizontal.ant-divider-with-text) {
    margin-top: 0;
  }
  h2 {
    font-size: 17px;
    font-weight: 600;
  }
</style>
